<template>
  <uni-nav-bar :border="false" title="订单" fixed />

  <!-- Tab 切换组件 -->
  <view class="tab-container">
    <uni-segmented-control
      :current="currentTabIndex"
      :values="tabOptions"
      style-type="button"
      active-color="#ff6b35"
      @clickItem="handleTabChange"
    />
  </view>

  <view class="page-container">
    <!-- 订单内容容器 -->
    <view class="order-container">
      <!-- 筛选栏 -->
      <view class="filter-section">
        <FilterDateTimer
          @dateChange="handleDateChange"
          @filter="handleFilter"
        />
      </view>

      <!-- 头部统计数据 (仅线下订单显示) -->
      <view v-if="orderType === 'offline'" class="stats-header">
        <view class="stats-row-top">
          <view class="stat-item-large">
            <text class="stat-value-large"
              >¥ {{ statistics.totalTransaction }}</text
            >
            <text class="stat-label">交易金额</text>
          </view>
          <view class="stat-item-large">
            <text class="stat-value-large">¥ {{ statistics.totalRefund }}</text>
            <text class="stat-label">退款金额</text>
          </view>
        </view>
        <view class="stats-row-bottom">
          <view class="stat-item-small">
            <text class="stat-value-small"
              >¥ {{ statistics.actualIncome }}</text
            >
            <text class="stat-label-small"
              >实收
              <uni-icons type="help-filled" size="12" color="#999"></uni-icons
            ></text>
          </view>
          <view class="stat-item-small">
            <text class="stat-value-small"
              >¥ {{ statistics.merchantPoints }}</text
            >
            <text class="stat-label-small"
              >商家积分
              <uni-icons type="help-filled" size="12" color="#999"></uni-icons
            ></text>
          </view>
          <view class="stat-item-small">
            <text class="stat-value-small">¥ {{ statistics.platformFee }}</text>
            <text class="stat-label-small"
              >平台手续费
              <uni-icons type="help-filled" size="12" color="#999"></uni-icons
            ></text>
          </view>
        </view>
      </view>

      <!-- 订单列表 -->
      <view class="order-list">
        <view
          class="order-item"
          v-for="order in filteredOrders"
          :key="order.id"
          @click="handleOrderClick(order)"
        >
          <!-- 订单标题和状态 -->
          <view class="order-header">
            <text class="order-title">{{ order.title }}</text>
            <view class="order-status" :class="getStatusClass(order.status)">
              <text>{{ order.statusText }}</text>
            </view>
          </view>

          <!-- 金额和手续费 -->
          <view class="order-amount">
            <text class="order-total">¥ {{ order.totalAmount }}</text>
            <text class="order-fee">(手续费 ¥ {{ order.fee }})</text>
          </view>

          <!-- 时间和交易额 -->
          <view class="order-info">
            <text class="order-time">{{ order.createTime }}</text>
            <text class="order-transaction"
              >交易额：¥ {{ order.transactionAmount }}</text
            >
          </view>
        </view>

        <!-- 空状态 -->
        <view v-if="filteredOrders.length === 0" class="empty-state">
          <text class="empty-text">暂无订单数据</text>
        </view>

        <!-- 加载更多 -->
        <view v-if="hasMore && filteredOrders.length > 0" class="load-more">
          <uni-load-more :status="loadStatus" />
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { onShow, onReachBottom } from "@dcloudio/uni-app";
import FilterDateTimer from "@/pages/order/components/FilterDateTimer.vue";
import FilterModal from "@/pages/order/components/FilterModal.vue";
import dayjs from "dayjs";
import { getOfflineOrderData, getOfflineOrderList } from "@/api/shop";
import { useUserStore } from "@/store/modules/user";
import { useStoreStore } from "@/store/modules/store";
import { useRequest } from "ahooks-vue";

const userStore = useUserStore();
const storeStore = useStoreStore();

// Tab 切换相关
const tabOptions = ref(["线上订单", "线下订单"]);
const currentTabIndex = ref(1); // 默认选中线下订单
const orderType = ref("offline"); // 'online' | 'offline'

// 是否已初始化（避免重复加载）
const isInitialized = ref(false);

// 当前选中的日期（默认显示当前年月）
const now = dayjs();
const currentDate = ref({
  year: now.year(),
  month: now.month() + 1, // dayjs的月份是0-11，需要+1
});

// 筛选弹窗引用
const filterModalRef = ref(null);

// 筛选条件
const filterConditions = ref({
  orderType: "all",
  orderStatus: "all",
  orderNo: "",
  buyerPhone: "",
});

// 统计数据
const statistics = ref({
  totalTransaction: "0.00", // a - 交易金额
  totalRefund: "0.00", // b - 退款金额
  actualIncome: "0.00", // c - 实收
  merchantPoints: "0.00", // d - 商家积分
  platformFee: "0.00", // e - 平台手续费
});

// 订单列表数据
const orders = ref([]);

// 分页参数
const pagination = ref({
  offset: 1, // 当前页码
  limit: 10, // 每页数量
  total: 0, // 总数
});

// 获取订单统计数据
const { loading: dataLoading, run: getOfflineOrderDataRun } = useRequest(
  () => {
    const selectTime = `${currentDate.value.year}-${String(
      currentDate.value.month
    ).padStart(2, "0")}`;
    return getOfflineOrderData({
      merchantId: storeStore.storeId,
      userId: userStore.userId,
      selectTime,
    });
  },
  {
    manual: true,
    onSuccess: (res) => {
      console.log("订单统计数据响应:", res);
      if (res && res.data) {
        // 更新统计数据
        statistics.value = {
          totalTransaction: (res.data.a || 0).toFixed(2), // a - 交易金额
          totalRefund: (res.data.b || 0).toFixed(2), // b - 退款金额
          actualIncome: (res.data.c || 0).toFixed(2), // c - 实收
          merchantPoints: (res.data.d || 0).toFixed(2), // d - 商家积分
          platformFee: (res.data.e || 0).toFixed(2), // e - 平台手续费
        };
      }
    },
    onError: (err) => {
      console.error("获取订单统计数据失败:", err);
    },
  }
);

// 获取订单列表
const { loading: listLoading, run: getOfflineOrderListRun } = useRequest(
  () => {
    const selectTime = `${currentDate.value.year}-${String(
      currentDate.value.month
    ).padStart(2, "0")}`;

    return getOfflineOrderList({
      isMerchant: 1, // 商家订单
      merchantId: storeStore.storeId,
      userId: userStore.userId,
      offset: pagination.value.offset,
      limit: pagination.value.limit,
      plural: orderType.value === "online" ? 1 : 4, // 1.普通商品订单 4.线下支付订单
      selectTime, // 查询时间 yyyy-MM
      status:
        filterConditions.value.orderStatus === "all"
          ? undefined
          : filterConditions.value.orderStatus,
    });
  },
  {
    manual: true,
    onSuccess: (res) => {
      console.log("订单列表响应:", res);
      if (res && res.data) {
        // 映射订单数据 (注意：数据在 rows 字段中)
        const newOrders = (res.data.rows || []).map((item) => ({
          id: item.id, // 订单ID（用于跳转详情页）
          orderTradeId: item.orderTradeId, // 订单号
          createTime: item.tradeTime
            ? dayjs(item.tradeTime).format("YYYY-MM-DD HH:mm:ss")
            : "", // 订单创建时间
          payTime: item.payTime
            ? dayjs(item.payTime).format("YYYY-MM-DD HH:mm:ss")
            : "", // 支付时间
          transactionAmount: (item.tradeMoney || 0).toFixed(2), // 交易金额
          totalAmount: (
            (item.realMoney !== undefined ? item.realMoney : item.tradeMoney) ||
            0
          ).toFixed(2), // 商户到手价
          fee: (item.feeMoney || 0).toFixed(2), // 手续费
          merchantName: item.merchantName || "", // 商户名称
          goodsName: item.tradeGoodsName || "线下收款", // 商品名称
          title: getOrderTitle(item), // 订单标题
          status: getOrderStatus(item.tradeStatus), // 订单状态
          statusText: getOrderStatusText(item.tradeStatus), // 状态文本
          orderNo: item.orderTradeId, // 订单编号
          buyerPhone: item.recipientsMobile, // 买家手机号
          orderType: getOrderType(item.plural), // 订单类型
          // 保留原始数据
          raw: item,
        }));

        // 如果是第一页，直接替换；否则追加
        if (pagination.value.offset === 1) {
          orders.value = newOrders;
        } else {
          orders.value = [...orders.value, ...newOrders];
        }

        // 更新总数
        pagination.value.total = res.data.total || 0;

        // 更新加载状态
        if (orders.value.length >= pagination.value.total) {
          hasMore.value = false;
          loadStatus.value = "noMore";
        } else {
          hasMore.value = true;
          loadStatus.value = "more";
        }
      }
    },
    onError: (err) => {
      console.error("获取订单列表失败:", err);
      uni.showToast({
        title: "获取订单列表失败",
        icon: "none",
      });
      loadStatus.value = "more";
    },
  }
);

// Tab 切换处理
const handleTabChange = (e) => {
  const index = e.currentIndex;
  currentTabIndex.value = index;
  orderType.value = index === 0 ? "online" : "offline";

  // 重置分页和订单列表
  pagination.value.offset = 1;
  orders.value = [];

  // 重新加载数据
  refreshData();
};

// 获取订单标题
const getOrderTitle = (order) => {
  const goodsName = order.tradeGoodsName || "线下收款";
  const merchantName = order.merchantName || "";

  // 如果有商户名称，显示：商品名 - 商户名
  if (merchantName) {
    // 限制长度，避免太长
    const shortMerchant =
      merchantName.length > 10
        ? merchantName.substring(0, 10) + "..."
        : merchantName;
    return `${goodsName} - ${shortMerchant}`;
  }

  // 否则只显示商品名
  return goodsName;
};

// 获取订单状态
const getOrderStatus = (status) => {
  const statusMap = {
    0: "pending", // 待支付
    1: "pending", // 待发货
    2: "pending", // 待收货
    3: "cancelled", // 已取消
    4: "completed", // 已完成
  };
  return statusMap[status] || "default";
};

// 获取订单状态文本
const getOrderStatusText = (status) => {
  const textMap = {
    0: "待支付",
    1: "待发货",
    2: "待收货",
    3: "已取消",
    4: "已完成",
  };
  return textMap[status] || "未知";
};

// 获取订单类型
const getOrderType = (plural) => {
  const typeMap = {
    1: "goods", // 普通商品订单
    4: "offline", // 线下支付订单
    5: "large", // 大额收款订单
  };
  return typeMap[plural] || "other";
};

// 加载状态
const loadStatus = ref("more");
const hasMore = ref(false);

// 根据筛选条件筛选订单（日期已通过接口参数筛选）
const filteredOrders = computed(() => {
  if (!orders.value || orders.value.length === 0) {
    return [];
  }

  return orders.value.filter((order) => {
    // 订单编号筛选
    const orderNoMatch =
      !filterConditions.value.orderNo ||
      (order.orderNo && order.orderNo.includes(filterConditions.value.orderNo));

    // 买家手机号筛选
    const buyerPhoneMatch =
      !filterConditions.value.buyerPhone ||
      (order.buyerPhone &&
        order.buyerPhone.includes(filterConditions.value.buyerPhone));

    // 订单类型筛选
    const orderTypeMatch =
      filterConditions.value.orderType === "all" ||
      order.orderType === filterConditions.value.orderType;

    // 订单状态筛选
    const orderStatusMatch =
      filterConditions.value.orderStatus === "all" ||
      order.status === filterConditions.value.orderStatus;

    return (
      orderNoMatch && buyerPhoneMatch && orderTypeMatch && orderStatusMatch
    );
  });
});

// 刷新数据（重置分页并重新加载）
const refreshData = () => {
  pagination.value.offset = 1;
  orders.value = [];
  // 同时获取统计数据和订单列表
  getOfflineOrderDataRun();
  getOfflineOrderListRun();
};

// 处理日期变更（用户点击确定按钮后触发）
const handleDateChange = (date) => {
  console.log(
    "日期变更:",
    date,
    "当前日期:",
    currentDate.value,
    "已初始化:",
    isInitialized.value
  );

  // 检查日期是否真的改变了
  const dateChanged =
    currentDate.value.year !== date.year ||
    currentDate.value.month !== date.month;

  // 先更新当前日期
  currentDate.value = date;

  // 只有在初始化完成后且日期真的改变了才重新请求数据
  if (isInitialized.value && dateChanged) {
    console.log("日期改变，重新加载数据");
    refreshData();
  } else {
    console.log(
      "跳过加载 - 已初始化:",
      isInitialized.value,
      "日期改变:",
      dateChanged
    );
  }
};

// 处理筛选按钮点击（日期筛选）
const handleFilter = (date) => {
  console.log("筛选日期:", date);
  currentDate.value = date;
  // 重新请求数据
  refreshData();
};

// 处理订单项点击
const handleOrderClick = (order) => {
  console.log("点击订单:", order);
  // 跳转到订单详情页
  // id: 订单ID（用于查询订单详情）
  // type: 订单类型（根据当前 tab 决定：offline=线下订单，online=线上订单）
  uni.navigateTo({
    url: `/pages/order/detail?id=${order.id}&type=${orderType.value}`,
  });
};

// 显示筛选弹窗
const showFilterModal = () => {
  filterModalRef.value.open();
};

// 处理筛选确认
const handleFilterConfirm = (filterData) => {
  console.log("筛选条件:", filterData);
  filterConditions.value = filterData;

  // 重新加载订单列表
  refreshData();

  // 构建筛选描述
  const filterDesc = [];
  if (filterData.orderType !== "all") {
    filterDesc.push(`类型: ${filterData.orderType}`);
  }
  if (filterData.orderStatus !== "all") {
    filterDesc.push(`状态: ${filterData.orderStatus}`);
  }
  if (filterData.orderNo) {
    filterDesc.push(`订单号: ${filterData.orderNo}`);
  }
  if (filterData.buyerPhone) {
    filterDesc.push(`手机号: ${filterData.buyerPhone}`);
  }

  const message = filterDesc.length > 0 ? filterDesc.join(", ") : "已重置筛选";

  uni.showToast({
    title: message,
    icon: "none",
    duration: 2000,
  });
};

// 获取状态样式类
const getStatusClass = (status) => {
  switch (status) {
    case "completed":
      return "status-completed";
    case "pending":
      return "status-pending";
    case "cancelled":
      return "status-failed";
    default:
      return "status-default";
  }
};

// 加载更多
const loadMore = () => {
  if (!hasMore.value || listLoading.value) {
    return;
  }

  loadStatus.value = "loading";
  pagination.value.offset += 1;
  getOfflineOrderListRun();
};

// 初始化数据加载
const initData = () => {
  console.log("🔄 初始化订单数据");

  // 从本地缓存恢复店铺信息和用户信息
  storeStore.hydrateFromStorage();
  userStore.hydrateFromStorage();

  // 打印调试信息
  console.log("商户ID:", storeStore.storeId);
  console.log("用户信息:", userStore.userInfo);
  console.log("用户ID:", userStore.userId);

  // 加载初始订单数据
  if (storeStore.storeId && userStore.userId) {
    // 先标记为已初始化，防止 FilterDateTimer 的初始化 dateChange 事件触发重复加载
    isInitialized.value = true;
    // 加载数据
    refreshData();
  } else {
    console.warn("缺少商户ID或用户ID，无法加载订单列表");
    uni.showToast({
      title: "缺少必要信息，请先登录",
      icon: "none",
    });
  }
};

// 页面显示时刷新数据（包括切换店铺后返回）
onShow(() => {
  initData();
});

// 页面触底事件
onReachBottom(() => {
  loadMore();
});
</script>

<style lang="scss" scoped>
// Tab 容器样式
.tab-container {
  position: fixed;
  top: 88rpx;
  left: 0;
  right: 0;
  z-index: 99;
  background-color: #fff;
  padding: 20rpx 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);

  ::v-deep .uni-segmented-control {
    border-radius: 8rpx;
    overflow: hidden;
  }

  ::v-deep .segmented-control__item {
    font-size: 28rpx;
    font-weight: 500;
  }
}

.page-container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

// 订单容器
.order-container {
  padding-top: 210rpx; // Tab + 筛选栏高度
  min-height: 100vh;
}

.filter-section {
  position: fixed;
  top: 200rpx;
  left: 0;
  right: 0;
  z-index: 99;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  padding: 0 30rpx;
  border-bottom: 2rpx solid #f0f0f0;
}

.filter-button {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 10rpx 24rpx;
  border-radius: 20rpx;
  cursor: pointer;
}

.filter-text {
  font-size: 28rpx;
  color: #666;
}

// 头部统计区域
.stats-header {
  background-color: #fff;
  padding: 24rpx 30rpx;
  margin: 20rpx 30rpx;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
}

.stats-row-top {
  display: flex;
  justify-content: space-between;
  gap: 40rpx;
  margin-bottom: 24rpx;
  padding-bottom: 24rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.stats-row-bottom {
  display: flex;
  justify-content: space-between;
  gap: 20rpx;
}

.stat-item-large {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.stat-item-small {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 6rpx;
}

.stat-value-large {
  font-size: 40rpx;
  font-weight: 700;
  color: #333;
}

.stat-value-small {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
}

.stat-label {
  font-size: 24rpx;
  color: #666;
}

.stat-label-small {
  font-size: 20rpx;
  color: #999;
  display: flex;
  align-items: center;
  gap: 4rpx;
}

.order-list {
  padding: 0 30rpx 20rpx;
}

.order-item {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx 24rpx;
  margin-bottom: 16rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
  cursor: pointer;
  transition: all 0.3s ease;

  &:active {
    transform: scale(0.98);
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
  }
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12rpx;
}

.order-title {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  font-weight: 400;
  margin-right: 16rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.order-status {
  padding: 4rpx 12rpx;
  border-radius: 6rpx;
  font-size: 22rpx;
  text-align: center;
  white-space: nowrap;
  flex-shrink: 0;
}

.status-completed {
  background-color: #e8f5e9;
  color: #4caf50;
}

.status-pending {
  background-color: #fff7e6;
  color: #fa8c16;
}

.status-failed {
  background-color: #fff2f0;
  color: #ff4d4f;
}

.status-default {
  background-color: #f5f5f5;
  color: #666;
}

.order-amount {
  display: flex;
  align-items: baseline;
  justify-content: flex-end;
  gap: 8rpx;
  margin-bottom: 12rpx;
}

.order-total {
  font-size: 36rpx;
  font-weight: 700;
  color: #333;
}

.order-fee {
  font-size: 22rpx;
  color: #999;
}

.order-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-time {
  font-size: 22rpx;
  color: #999;
}

.order-transaction {
  font-size: 22rpx;
  color: #666;
}

.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

.load-more {
  padding: 20rpx 0;
}
</style>
